package com.application.Network;

import it.unipr.ce.dsg.s2p.sip.Address;
import android.content.Intent;
import android.util.Log;

import com.application.Activity.MESApplication;
import com.application.Activity.frmMatKetNoiActivity;
import com.application.Controller.NetworkController;

public class PingThread extends Thread {
	// boolean running=false;
	private String name;
	private static PingThread instant = null;
	private static boolean isRunning=false;
	private PingThread() {
		super();
	}

	public PingThread(String name) {
		this.name = name;		
	}

	public static synchronized PingThread getInstance(String name) {
		if (instant == null) {
			instant = new PingThread(name);
		}
		return instant;
	}

//	@Override
//	public void run() {
//		// running=true;
//		if (NetworkController.thanhLapNhomIP != "") {
//			while (isRunning) {
//				//Log.d("Phu", "PingThread running: " + this.name);
//				if (!NetworkController.getStated()) {
//
//					if (!frmMatKetNoiActivity.isShowed) {
//						frmMatKetNoiActivity.isShowed=true;
//						Intent intent = new Intent(MESApplication.getAppContext(), frmMatKetNoiActivity.class);
//						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						MESApplication.getAppContext().startActivity(intent);
//					}
//				} else {
//
//					try {						
//						NetworkController.setStated(false);
//						NetworkController.sendPing(new Address(NetworkController.thanhLapNhomIP));
//						sleep(5000);
//					} catch (InterruptedException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//						//NetworkController.isConnected = true;
//						continue;
//					}
//				}
//
//			}
//		}
//		Log.d("Phu","ket thuc thread"+name); 
//	}
	@Override
	public void run() {
		Log.d("Phu","Start pingthread: "+name);
		isRunning=true;
		if (NetworkController.thanhLapNhomIP != "") {
			while (isRunning) {				
				if (!NetworkController.getStated()) {
					Log.d("Phu","running..");
					if (!frmMatKetNoiActivity.isShowed) {
						frmMatKetNoiActivity.isShowed=true;
						Intent intent = new Intent(MESApplication.getAppContext(), frmMatKetNoiActivity.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						MESApplication.getAppContext().startActivity(intent);
						isRunning=false;
					}
				} else {

					try {		
						Log.d("Phu","sleep 5s..");
						NetworkController.setStated(false);
						NetworkController.sendPing(new Address(NetworkController.thanhLapNhomIP));
						sleep(5000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						NetworkController.setStated(false);
						Log.d("Phu","catch mat roi");
						continue;
					}
				}

			}
		}
		Log.d("Phu","ket thuc thread"+name);
	}
	public static boolean getIsRunning(){
		return isRunning;
	}
	public static void setRunning(boolean running){
		isRunning=running;
	}
}
